package com.hmdp.utils;


import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private StringRedisTemplate stringRedisTemplate;
    private String name;
    private static final String LOCK_PREFIX = "lock:";
    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }

    @Override
    public Boolean tryLock(long timeout) {
        long threadId = Thread.currentThread().getId();
        Boolean ifAbsent = stringRedisTemplate
                .opsForValue().setIfAbsent(LOCK_PREFIX + name, threadId+"", timeout, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(ifAbsent);
    }

    @Override
    public void unlock() {
        stringRedisTemplate.delete(LOCK_PREFIX + name);
    }
}
